package com.sgb.kjwl.viewmodel.transport;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.sgb.capital.utils.Utils;
import com.sgb.kjwl.api.APIManager;
import com.sgb.kjwl.api.NewAPIManager;
import com.sgb.kjwl.model.entity.MyCarInfoEntity;
import com.sgb.kjwl.model.entity.self.CarInfoEntity;
import com.sgb.kjwl.model.entity.transport.DriverAuthEntity;
import com.sgb.kjwl.model.entity.transport.DrivingLicenseOCREntity;
import com.sgb.kjwl.utils.AddressHelper;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.EntityConversion;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.activity.self.logistics.AddCarActivity;
import com.sgb.kjwl.view.ui.activity.transport.SelfCarDetailActivity;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.common.base.BaseViewModel;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.dialog.RoundDialog;
import com.swgk.core.event.EventConstant;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NullableUtil;

import org.greenrobot.eventbus.EventBus;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;

public class AddSelfCarViewModel extends BaseViewModel {
    public MutableLiveData<DrivingLicenseOCREntity> ldOcr = new MutableLiveData<>();
    public MutableLiveData<CarInfoEntity> ldCar = new MutableLiveData<>();
    public MutableLiveData<String> ldMain = new MutableLiveData<>();
    public MutableLiveData<String> ldSub = new MutableLiveData<>();
    public MutableLiveData<String> ldActual = new MutableLiveData<>();

    public AddSelfCarViewModel(@NonNull @NotNull Application application) {
        super(application);
    }

    /**
     * 获取车辆详情
     */
    public void getCarDetail(Context context, long no) {
        DialogHelper.showProgressDialog(context, "加载中");
        NewAPIManager.getInstance().getLogisticsAPI().getJingDriverDetail(no).enqueue(new ICallBack<BaseEntity<MyCarInfoEntity>>() {
            @Override
            public void onSuccess(BaseEntity<MyCarInfoEntity> data) {
                ldCar.postValue(EntityConversion.modelA2B(data.getData(), CarInfoEntity.class));
            }

            @Override
            public void onFail() {
                ldCar.postValue(new CarInfoEntity());
            }
        });
    }

    /**
     * 获取定位信息
     */
    public void getLocation(Context context) {
        AddressHelper.getInstance().getCurrentLocation(context, entity -> {
            if (entity == null || ldCar.getValue() == null) return;
            ldCar.getValue().setLatitude(entity.getLatitude());
            ldCar.getValue().setLongitude(entity.getLongitude());
            ldCar.getValue().setProvinceName(entity.getProvince());
            ldCar.getValue().setProvinceNo(entity.getProvinceNo());
            ldCar.getValue().setCityName(entity.getCity());
            ldCar.getValue().setCityNo(entity.getCityNo());
            ldCar.getValue().setDistrictName(entity.getDistrict());
            ldCar.getValue().setDistrictNo(entity.getDistrictNo());
            ldCar.getValue().setDetailAddress(entity.getSnippet());
        });
    }

    /**
     * 上传图片
     */
    public void uploadFile(Context context, File file, int type) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(context, null, "文件上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                //选择图片类型 1:主页 2:副页 3:车辆45度图
                if (data.getData() == null) {
                    uploadFail(type);
                    return;
                }
                if (type == AddCarActivity.TYPE_SUB) {
                    ldSub.postValue(data.getData().toString());
                } else if (type == AddCarActivity.TYPE_ACTUAL) {
                    ldActual.postValue(data.getData().toString());
                }
            }

            @Override
            public void onFail() {
                uploadFail(type);
            }
        });
    }

    /**
     * 上传图片且识别驾驶证主页
     */
    public void uploadFileWithOCR(Context context, File file) {
        Map<String, RequestBody> photos = new HashMap<>();
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        photos.put("file" + "\"; filename=\"" + "image.jpg\"", requestBody);
        DialogHelper.showProgressDialog(context, null, "文件上传中...", 0, false, null).setCanceledOnTouchOutside(true);
        //更换接口
        APIManager.getInstance().getUploadAPI().uploadFile(photos).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data.getData() == null) {
                    uploadFail(AddCarActivity.TYPE_MAIN);
                    return;
                }
                ldMain.postValue(data.getData().toString());
            }

            @Override
            public void onFail() {
                uploadFail(AddCarActivity.TYPE_MAIN);
            }
        });
    }

    /**
     * 上传失败
     */
    private void uploadFail(int type) {
        if (type == AddCarActivity.TYPE_MAIN) {
            ldMain.postValue("");
        } else if (type == AddCarActivity.TYPE_SUB) {
            ldSub.postValue("");
        } else if (type == AddCarActivity.TYPE_ACTUAL) {
            ldActual.postValue("");
        }
    }

    /**
     * 行驶证ocr识别
     */
    public void carOcr(Context context) {
        if (ldCar.getValue() == null) return;
        Map<String, Object> map = new HashMap<>();
        map.put("vehicleLicense", ldCar.getValue().getVehicleLicense());
        map.put("drivingLicensePage", ldCar.getValue().getDrivingLicensePage());
        DialogHelper.showProgressDialog(context, "加载中");
        //主页和副页数据
        NewAPIManager.getInstance().getLogisticsAPI().operateAuthOCR(map).enqueue(new ICallBack<BaseEntity<DrivingLicenseOCREntity>>() {
            @Override
            public void onSuccess(BaseEntity<DrivingLicenseOCREntity> data) {
                ldOcr.postValue(data.getData());
            }

            @Override
            public void onFailure(Call<BaseEntity<DrivingLicenseOCREntity>> call, Throwable t) {
                onFail();
                onFinally();
            }

            @Override
            public void onFail() {
                showOcrErrorDialog(context);
            }
        });
    }

    /**
     * 车辆提交审核
     */
    public void authCar(Context context) {
        if (ldCar.getValue() == null) return;
        String main = ldCar.getValue().getVehicleLicense();
        if (TextUtils.isEmpty(main)) {
            MToast.showToast(context, "请先上传行驶证主页");
            return;
        }
        String sub = ldCar.getValue().getDrivingLicensePage();
        if (TextUtils.isEmpty(sub)) {
            MToast.showToast(context, "请先上传行驶证副页");
            return;
        }
        String car = ldCar.getValue().getCarImage();
//        if (TextUtils.isEmpty(car)) {
//            MToast.showToast(context, "请先上传车辆45度照片");
//            return;
//        }
        if (TextUtils.isEmpty(ldCar.getValue().getCarNumber())) {
            MToast.showToast(context, "请先输入车牌号");
            return;
        }
        if (!Utils.isPlateLogistics(ldCar.getValue().getCarNumber())){
            MToast.showToast(context, "请输入正确的车牌号");
            return;
        }
        if (TextUtils.isEmpty(ldCar.getValue().getImageApprovedLoadingQuality())) {
            MToast.showToast(context, "先输入核定载质量");
            return;
        }
        if (ldCar.getValue().getCarLen() == 0) {
            MToast.showToast(context, "请先输入车长");
            return;
        }
        if (TextUtils.isEmpty(ldCar.getValue().getDetailAddress())) {
            MToast.showToast(context, "请先输入住址");
            return;
        }

        if (!TextUtils.isEmpty(ldCar.getValue().getImageNumber())) {
            if (ldCar.getValue().getImageNumber().length() != 12) {
                MToast.showToast(context, "请输入12位档案编号.");
                return;
            }
        }

        if (TextUtils.isEmpty(ldCar.getValue().getLinkman())) {
            MToast.showToast(context, "请输入车辆负责人");
            return;
        }
        if (TextUtils.isEmpty(ldCar.getValue().getLinkmanPhone())) {
            MToast.showToast(context, "请输入负责人的电话");
            return;
        }
//        if (!TextUtils.isEmpty(ldCar.getValue().getLinkmanPhone()) && !CheckUtils.isPhoneNumberValid(ldCar.getValue().getLinkmanPhone())) {
//            MToast.showToast(context, "请输入正确的电话");
//            return;
//        }

        //判断不是人工审核的情况下车牌号是否一致
//        if (ldOcr.getValue() != null && !ldOcr.getValue().isManualCheck()
//                && !ldCar.getValue().getCarNumber().equals(ldCar.getValue().getImageCarNumber())) {
//            showCarNumberErrorDialog(context);
//            return;
//        }
        Map<String, Object> map = new HashMap<>();
        map.put("authIndex", 1);
        if (ldCar.getValue().getId() != 0) {
            map.put("id", ldCar.getValue().getId());
        }
        //人工审核参数 manualCheck
        if (ldOcr.getValue().isManualCheck()) {
            map.put("manualCheck", true);
        }
        //图片信息
        map.put("vehicleLicense", main);
        map.put("drivingLicensePage", sub);
        map.put("carImage", car);
        //页面输入框实际参数
        map.put("carNumber", ldCar.getValue().getCarNumber());
        map.put("carlenName", NumberUtil.trim0(ldCar.getValue().getCarLen()));
        map.put("weight", ldCar.getValue().getWeight());
        //ocr识别参数
        map.put("imageDateOfIssue", ldOcr.getValue().getImageDateOfIssue());
        map.put("imageNatureOfUse", ldOcr.getValue().getImageNatureOfUse());
        map.put("imageIssuingAuthority", ldOcr.getValue().getImageIssuingAuthority());
        map.put("imageSizeL", ldOcr.getValue().getImageSizeL());
        map.put("imageSizeW", ldOcr.getValue().getImageSizeW());
        map.put("imageVehicleIdentifier", ldOcr.getValue().getImageVehicleIdentifier());
        map.put("imageTotalMass", ldOcr.getValue().getImageTotalMass());
        map.put("imageRegistrationDate", ldOcr.getValue().getImageRegistrationDate());
        map.put("imageApprovedLoadingQuality", ldCar.getValue().getImageApprovedLoadingQuality());
        map.put("imageCarNumber", ldOcr.getValue().getImageCarNumber());
        map.put("imageVehicleEnergyType", ldOcr.getValue().getImageVehicleEnergyType());
        map.put("imageCarType", ldOcr.getValue().getImageCarType());
        map.put("imageHolder", ldOcr.getValue().getImageHolder());
        map.put("imageSizeH", ldOcr.getValue().getImageSizeH());
        if (!TextUtils.isEmpty(ldOcr.getValue().getImageNumber())) {
            map.put("imageNumber", ldOcr.getValue().getImageNumber());
        } else {
            map.put("imageNumber", "");
        }
        //添加定位信息
        map.put("imageVehicleAddress", ldCar.getValue().getDetailAddress());
        map.put("imageVehicleCity", ldCar.getValue().getCityName());
        map.put("imageVehicleCityNo", ldCar.getValue().getCityNo());
        map.put("imageVehicleDistrict", ldCar.getValue().getDistrictName());
        map.put("imageVehicleDistrictNo", ldCar.getValue().getDistrictNo());
        map.put("imageVehicleLat", ldCar.getValue().getImageVehicleLat());
        map.put("imageVehicleLon", ldCar.getValue().getImageVehicleLon());
        map.put("imageVehicleProvince", ldCar.getValue().getProvinceName());
        map.put("imageVehicleProvinceNo", ldCar.getValue().getProvinceNo());

        map.put("linkman", ldCar.getValue().getLinkman());
        map.put("linkmanPhone", ldCar.getValue().getLinkmanPhone());
    /*    map.put("longitude", ldCar.getValue().getLongitude());
        map.put("latitude", ldCar.getValue().getLatitude());
        map.put("provinceNo", ldCar.getValue().getProvinceNo());
        map.put("provinceName", ldCar.getValue().getProvinceName());
        map.put("cityNo", ldCar.getValue().getCityNo());
        map.put("cityName", ldCar.getValue().getCityName());
        map.put("districtNo", ldCar.getValue().getDistrictNo());
        map.put("districtName", ldCar.getValue().getDistrictName());
        map.put("detailAddress", ldCar.getValue().getDetailAddress());*/
        DialogHelper.showProgressDialog(context, "加载中");
        NewAPIManager.getInstance().getLogisticsAPI().operateDriverAuth(map).enqueue(new ICallBack<BaseEntity<DriverAuthEntity>>() {
            @Override
            public void onSuccess(BaseEntity<DriverAuthEntity> data) {
                //认证成功
                EventBus.getDefault().post(LogisticsEvent.make().setMessageTag(EventConstant.EVENT_CARINFO_COMMIT));
                String no = data.getData().getNo();
                //id不为0则为编辑行驶证，直接返回来源页面
                if (ldCar.getValue().getId() != 0) {
                    ((Activity) context).finish();
                } else {
                    showSuccessDialog(context, NumberUtil.convertToLong(no));
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<DriverAuthEntity>> call, Throwable t) {
                //复写失败方法移除父类访问失败逻辑
            }

            @Override
            public void onFailureWithEntity(BaseEntity entity) {
                //错误提示弹窗
                if (entity == null) {
                    showErrorDialog(context, "接口响应失败");
                } else if ("217".equals(entity.getCode())) {
                    showOtherCarNumberDialog(context, entity.getMsg());
                } else if ("218".equals(entity.getCode())) {
                    showCarNumberErrorDialog(context, entity.getMsg());
                } else {
                    showErrorDialog(context, entity.getMsg());
                }
                onFinally();
            }
        });
    }

    /**
     * 成功弹窗
     */
    private void showSuccessDialog(Context context, long no) {
       /* new RoundDialog.Builder(context)
                .title("车辆信息完善")
                .content("车辆添加成功，是否立即完善车辆信息")
                .cancelable(false)
                .confirmCallback(v -> {
                    //todo 跳转完善车辆信息页面
                    SelfCarInfoActivity.start(context,no);
                })
                .cancelCallback(v -> {
                    //todo 跳转车辆审核页面
                    SelfCarDetailActivity.start(context, no);
                })
                .dismissListener(dialog -> ((Activity) context).finish())
                .show();*/
        ((Activity) context).finish();
        //todo 跳转车辆审核页面
        SelfCarDetailActivity.start(context, no);
        // ActivityJump.jumpToActivity(context, SelfCarDetailActivity.class, Pair.create(RouterKey.NO, no));
    }

    /**
     * 车牌号未识别弹窗
     */
    private void showOcrErrorDialog(Context context) {
        ldCar.getValue().setLatitude(0);
        ldCar.getValue().setLongitude(0);
        new RoundDialog.Builder(context)
                .title("提示")
                .content("证照无法识别，可重新上传或填写后提交人工审核")
                .confirm("确定")
                .cancelable(false)
                .singleBtn(true)
                .confirmCallback(v -> ldOcr.postValue(new DrivingLicenseOCREntity(true)))
                .show();
    }

    /**
     * 车牌号不一致弹窗
     */
    private void showCarNumberErrorDialog(Context context, String content) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content(content)
                .cancel("提交")
                .confirm("暂不提交")
                .cancelable(false)
                .cancelCallback(v -> {
                    //设置人工审核并重新提交
                    NullableUtil.ofNullable(ldOcr.getValue()).ifPresent(entity -> entity.setManualCheck(true));
                    authCar(context);
                })
                .show();
    }

    /**
     * 修改其他车牌号弹窗
     */
    private void showOtherCarNumberDialog(Context context, String content) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content(content)
                .cancel("取消")
                .confirm("提交审核")
                .cancelable(false)
                .confirmCallback(v -> {
                    //设置人工审核并重新提交
                    NullableUtil.ofNullable(ldOcr.getValue()).ifPresent(entity -> entity.setManualCheck(true));
                    authCar(context);
                })
                .show();
    }

    /**
     * 错误提示弹窗
     */
    private void showErrorDialog(Context context, String content) {
        new RoundDialog.Builder(context)
                .title("提示")
                .content(DefaultUtil.getString(content))
                .confirm("确定")
                .cancelable(false)
                .singleBtn(true)
                .show();
    }
}
